package com.suyx.job.service.impl;


import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.suyx.job.dao.TuInfoRepository;
import com.suyx.job.entity.Page;
import com.suyx.job.entity.TuInfo;
import com.suyx.job.service.ITuInfoService;
import com.suyx.job.service.base.impl.MyServiceImpl;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/18 0018 11:50
 * @Description:
 */
@Slf4j
@Service
public class TuInfoServiceImpl extends MyServiceImpl<TuInfo,Integer> implements ITuInfoService {

    private TuInfoRepository tuInfoRepository;

    @Autowired
    public TuInfoServiceImpl(TuInfoRepository repository) {
        super(repository);
        this.tuInfoRepository = repository;
    }

    @Override
    public Page findTuPage(TuInfo tuInfo,Integer page, Integer limit) {
        return  new Page(
        		tuInfoRepository.findAll((Root<TuInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if(!StringUtils.isEmpty(tuInfo.getDevice())){
                        predicates.add(cb.equal(root.get("device").as(String.class), tuInfo.getDevice()));
                    }
                    if(!StringUtils.isEmpty(tuInfo.getStatus())){
                        predicates.add(cb.equal(root.get("status").as(String.class), tuInfo.getStatus()));
                    }
                    if(!StringUtils.isEmpty(tuInfo.getRoleId())){
                        predicates.add(cb.equal(root.get("roleId").as(Integer.class), tuInfo.getRoleId()));
                    }
                    return  query.where(predicates.toArray(new Predicate[0]))
                    		.orderBy(cb.asc(root.get("scene").as(String.class)),cb.asc(root.get("distance").as(Double.class)))
                    		.getRestriction();
                }, PageRequest.of(page,limit))
        );
    }


    
	@Override
	public void deleteByDeviceAndStatus(String device,String status) {
		tuInfoRepository.deleteByDeviceAndStatus(device,status);
	}

	@Override
	public List<TuInfo> findByDevice(String device, Sort sort) {
		return tuInfoRepository.findByDevice(device, sort);
	}

	@Override
	public List<TuInfo> findByRoleId(Integer roleId, Sort sort) {
		return tuInfoRepository.findByRoleId(roleId, sort);
	}

	@Override
	public void deleteByRoleIdAndStatus(Integer roleId, String status) {
		tuInfoRepository.deleteByRoleIdAndStatus(roleId, status);
	}

}
